package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.mapper.ActivityMapper;
import com.csxy.six.mapper.SigninMapper;
import com.csxy.six.entity.Activity;
import com.csxy.six.entity.Signin;
import com.csxy.six.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Autowired
    private SigninMapper signinMapper;

    @Override
    @Transactional
    public boolean joinActivity(Long activityId, Long userId) {
        Activity activity = baseMapper.selectById(activityId);
        if (activity == null ||
                activity.getMaxParticipants() != null &&
                        activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            return false;
        }

        // 检查是否已报名 - 参数顺序为 (userId, activityId)
        Signin existing = signinMapper.selectByUserAndActivity(userId, activityId);
        if (existing != null) {
            return false;
        }

        // 创建签到记录
        Signin signin = new Signin();
        signin.setActivityId(activityId);
        signin.setUserId(userId);
        signin.setIsPresent(false);
        signinMapper.insert(signin);

        // 更新活动人数
        activity.setCurrentParticipants(activity.getCurrentParticipants() + 1);
        baseMapper.updateById(activity);
        return true;
    }

    @Override
    public boolean signIn(Long activityId, Long userId) {
        // 参数顺序为 (userId, activityId)
        Signin signin = signinMapper.selectByUserAndActivity(userId, activityId);
        if (signin == null || signin.getIsPresent()) {
            return false;
        }

        signin.setSigninTime(new Date());
        signin.setIsPresent(true);
        signinMapper.updateById(signin);
        return true;
    }
}